package com.web.logindemo.service;

import com.web.logindemo.common.Constants;
import com.web.logindemo.config.RedisCache;
import com.web.logindemo.config.manager.AsyncManager;
import com.web.logindemo.config.manager.factory.AsyncFactory;
import com.web.logindemo.domain.model.LoginUser;
import com.web.logindemo.service.token.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Service;
import org.springframework.security.core.Authentication;

import javax.annotation.Resource;


@Service
public class LoginService {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 登陆验证
     *
     * @param username
     * @param password
     * @param code
     * @param uuid
     * @return
     */
    public String login(String username, String password, String code, String uuid) {
        validateCaptcha(username, code, uuid);
        Authentication authentication = null;
        try{
            authentication = authenticationManager.
                    authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }catch (Exception e){
            if(e instanceof BadCredentialsException){
                throw new RuntimeException("用户名与密码不匹配");
            }else {
                throw new RuntimeException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLoginFor(username, Constants.LOGIN_SUCCESS, "登录成功"));
        LoginUser loginUser =(LoginUser) authentication.getPrincipal();
        return tokenService.createToken(loginUser);
    }

    /**
     * 验证码校验
     *
     * @param username
     * @param code
     * @param uuid
     */
    private void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLoginFor(username, Constants.LOGIN_FAIL,
                    "验证码失效"));
            throw new RuntimeException("验证码失效");
        }
        if (!code.equals(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLoginFor(username, Constants.LOGIN_FAIL,
                    "验证码错误"));
            throw new RuntimeException("验证码错误");
        }
    }


}
